package com.lej.push

import android.content.Context
import android.os.Build
import com.heytap.msp.push.HeytapPushManager
import com.heytap.msp.push.callback.ICallBackResultService
import com.heytap.msp.push.mode.PushStatus
import com.huawei.agconnect.config.AGConnectServicesConfig
import com.huawei.hms.aaid.HmsInstanceId
import com.lej.core.BuildConfig
import com.lej.core.base.app
import com.lej.core.common.*
import com.lej.core.utils.extention.logI
import com.lej.dataservice.club.http.baseApiService
import com.lej.dataservice.club.http.checkData
import com.lej.push.BuildConfig.*
import com.lej.push.notification.NotificationUtils
import com.qmuiteam.qmui.util.QMUIDeviceHelper
import com.vivo.push.PushClient
import com.xiaomi.channel.commonutils.logger.LoggerInterface
import com.xiaomi.mipush.sdk.Logger
import com.xiaomi.mipush.sdk.MiPushClient
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.util.*


object PushUtils {
    ///如果需要注册到客户端id到后端
    var shouldBindClientId = false

    /**[registerCid] 返回推送的设备id之后 是否需要注册到后端*/
    fun init(context: Context, registerCid: Boolean = false) {
        NotificationUtils.createNotificationChannel(context)
        shouldBindClientId = registerCid
        ("注册推送->厂商:$osBrand").logI(LogTags.push)
        when (osBrand) {
            DEVICE_HUAWEI -> registerHWPushToken(context)
            DEVICE_XIAOMI -> {
                MiPushClient.registerPush(context, MIPUSH_ID, MIPUSH_KEY)
                if (app.isDebug) {
                    Logger.setLogger(context, object : LoggerInterface {
                        override fun setTag(p0: String?) {
                            p0?.logI("小米推送tag")
                        }
                        override fun log(p0: String?) {
                            p0?.logI("小米推送log")
                        }

                        override fun log(p0: String?, p1: Throwable?) {
                            p0?.logI("小米推送")
                        }
                    })
                }
            }
            ///支持oppo推送
            DEVICE_OPPO -> {
                HeytapPushManager.register(
                    context,
                    OPPO_PUSH_APP_KEY,
                    OPPO_PUSH_APP_SECRET,
                    object : ICallBackResultService {
                        override fun onRegister(p0: Int, p1: String?) {
                            p1?.let {
                                PCacheInfo.clientId = it
                                ("regid:$p1").logI("oppo 推送")
                            }
                        }

                        override fun onUnRegister(p0: Int) {
                        }

                        override fun onSetPushTime(p0: Int, p1: String?) {
                        }

                        override fun onGetPushStatus(p0: Int, p1: Int) {
                        }

                        override fun onGetNotificationStatus(p0: Int, p1: Int) {
                            if (p1 == PushStatus.NOTIFICATION_STATUS_CLOSE) {
                                ("设备通知栏被关闭了").logI("oppo 推送")
                            }
                        }
                    })
            }
            DEVICE_VIVO -> {
                // 在当前工程入口函数，建议在Application的onCreate函数中，添加以下代码
                ("注册推送->初始化vivo推送").logI(LogTags.push)
                PushClient.getInstance(context).initialize()
                // 打开push开关, 关闭为turnOffPush，详见api接入文档
                PushClient.getInstance(context).turnOnPush {
                    "推送打开${if (it == 0) "成功" else "失败"}".logI("vivo 推送")
                }
                if (app.isDebug) {
                    ("regid:" + PushClient.getInstance(context).regId).logI("vivo 推送")
                }
            }

            else -> {
                com.igexin.sdk.PushManager.getInstance().initialize(context.applicationContext)
                if (BuildConfig.DEBUG)
                    com.igexin.sdk.PushManager.getInstance()
                        .setDebugLogger(context.applicationContext) {
                            it.logI(LogTags.push)
                        }
            }

        }
    }

    ///注册华为推送
    private fun registerHWPushToken(context: Context) {
        MainScope().launch {
            kotlin.runCatching {
                val appId =
                    AGConnectServicesConfig.fromContext(context).getString("client/app_id")
                val token = HmsInstanceId.getInstance(context).getToken(appId, "HCM")
                "appId:${appId}华为推送Token".logI(LogTags.hwPush)
                PCacheInfo.clientId = token
                token.logI(LogTags.hwPush)
                if (shouldBindClientId) bindCid()
            }.onFailure {
                it.message?.logI(LogTags.hwPush)
            }
        }
    }

    fun bindCid() {
        if (PCacheInfo.clientId.isEmpty()) {
            "cid为空,不注册推送".logI(LogTags.push)
            return
        }
        _bindCid(PCacheInfo.clientId)
    }

    fun unBindCid() {
        _bindCid("")
    }

    /**解绑设备*/
    private fun _bindCid(cid : String?) {
        if (PCacheInfo.token.isEmpty()) {
            "用户还未登录,不注册推送".logI(LogTags.push)
            return
        }
        MainScope().launch {
            kotlin.runCatching {
                baseApiService.bindingCid(cid, maker = osNumber).checkData()
                "${PCacheInfo.clientId}->成功绑定到后端".logI(LogTags.push)
                shouldBindClientId = false
            }.onFailure {
                "${PCacheInfo.clientId}->绑定失败".logI(LogTags.push)
                it.message?.logI(LogTags.push)
            }
        }
    }
}

fun isSupportOppo(): Boolean {
    HeytapPushManager.init(app, true)
    return HeytapPushManager.isSupportPush()
}

///厂商品牌
val osBrand: String = when {
    QMUIDeviceHelper.isMIUI() -> DEVICE_XIAOMI
    QMUIDeviceHelper.isHuawei() -> DEVICE_HUAWEI
    isSupportOppo() -> DEVICE_OPPO
    QMUIDeviceHelper.isVivo() -> DEVICE_VIVO
    else -> Build.BRAND.lowercase(Locale.ROOT)
}

//1 默认 2 华为 3 小米 4 vivo 5 oppo
val osNumber: String = when (osBrand) {
    DEVICE_HUAWEI -> "2"
    DEVICE_XIAOMI -> "3"
    DEVICE_VIVO -> "4"
    DEVICE_OPPO -> "5"
    else -> "1"
}